package com.robot.mannge.common.config.security.handler;

/**
 * @Author: Smile
 * @Date: 2024/01/30/12:07
 * @Description:
 */

import com.alibaba.fastjson2.JSON;
import com.robot.mannge.common.result.BaseResult;
import com.robot.mannge.common.result.ResultCode;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 登录失败处理类
 */

@Component
public class LoginFailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        //设置响应的编码格式
        response.setContentType("application/json;charset=utf-8");

        ResultCode resultCode;
        //判断异常类型
        if (exception instanceof AccountExpiredException){
            //账户过期
            resultCode = ResultCode.LONGIN_EXPIRE;
        }else if (exception instanceof BadCredentialsException){
            resultCode = ResultCode.USER_PASSWORD_ERROR;
        } else if (exception instanceof CredentialsExpiredException) {
            resultCode = ResultCode.PASSWORD_EXPIRE;
        } else if (exception instanceof DisabledException) {
            resultCode = ResultCode.DisableUser;
        }else if (exception instanceof InternalAuthenticationServiceException){
            resultCode = ResultCode.NONEUSER;
        }else {
            resultCode = ResultCode.ERROR;
        }
        //转换json
        String jsonString = JSON.toJSONString(BaseResult.failed(resultCode, resultCode.message()));
        //输出到流
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(jsonString.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
